<?php
declare (strict_types = 1);

namespace app\middleware;

use app\lib\response\JSON;
use app\model\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Config;

class AdminLoginAuth
{
    /**
     * 登录验证中间件
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //get token from header
        $tokenStr = $request->header('Authorization');
        if(empty($tokenStr)){
            return JSON::error("",JSON::CODE_UNLOGIN_ERROR);
        }
        $parts = explode(' ',$tokenStr);
        if(count($parts)!=2 || empty($parts[1])){
            return JSON::error("",JSON::CODE_UNLOGIN_ERROR);
        }
        $token = $parts[1];
        $key = Config::get('app.jwt_key');
        //verify token
        try {
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
        } catch (\Throwable $th) {
            return JSON::error("",JSON::CODE_UNLOGIN_ERROR);
        }
       
        $request->session = [
            'uid' => $decoded->uid,
            'username' => $decoded->username,
        ];
        return $next($request);
    }
}
